<template>
  <div class="app-container">
    <div class="filter-condition_single">
      <label>条件搜索</label>
      <el-form
        size="mini"
        :inline="true"
        :model="filterCondition"
        style="flex: 1"
      >
        <el-form-item>
          <el-select
            v-model="filterCondition.groupId"
            size="mini"
            placeholder="请选择集团"
            clearable
            @change="handleChangeGroup"
            @clear="handleChangeGroup"
          >
            <el-option
              v-for="item in groups"
              :key="item.groupCode"
              :label="item.groupName"
              :value="item.groupId"
            >
              <span style="float: left">{{ item.groupCode }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.groupName }}</span>
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </div>
    <!-- <my-divider class="thin-divider" /> -->
    <el-row>
      <el-col :span="2">
        <label class="row-label">业务操作</label>
      </el-col>
      <el-col
        class="align-right"
        :span="22"
      >
        <el-button-group>
          <el-button
            v-permission="'ADD'"
            type="primary"
            icon="el-icon-plus"
            @click="handleCreate"
          >
            {{ $t('table.add') }}
          </el-button>
          <el-button
            v-permission="'MODIFY'"
            type="primary"
            icon="el-icon-edit"
            @click="handleUpdate"
          >
            {{ $t('table.edit') }}
          </el-button>
          <el-button
            v-permission="'DELETE'"
            type="primary"
            icon="el-icon-delete"
            class="deleted-button"
            @click="handleDelete"
          >
            {{ $t('table.delete') }}
          </el-button>
          <el-button
            type="primary"
            icon="el-icon-refresh"
            class="refresh-button"
            @click="handleRefresh"
          >
            {{ $t('tagsView.refresh') }}
          </el-button>
        </el-button-group>
      </el-col>
    </el-row>
    <div style="height: 600px;width: 100%">
      <pl-table
        :ref="tableRef"
        v-loading="listLoading"
        :data="list"
        use-virtual
        record-table-select
        :row-height="42"
        :pagination-show="false"
        border
        fit
        highlight-current-row
        header-row-class-name="table-header"
        cell-class-name="table-cell"
        style="width: 100%;"
        @row-click="handelRowClick"
        @row-dblclick="handleUpdate"
        @current-change="handleCurrentRowChange"
      >
        <pl-table-column type="expand">
          <template slot-scope="colDetailProps">
            <el-form
              size="mini"
              label-position="left"
            >
              <el-form-item label="组织编码">
                <span>{{ colDetailProps.row.organCode }}</span>
              </el-form-item>
              <el-form-item label="组织简称">
                <span>{{ colDetailProps.row.shortName }}</span>
              </el-form-item>
              <el-form-item label="集团">
                <span>{{ colDetailProps.row.groupName }}</span>
              </el-form-item>
              <el-row>
                <el-col :span="12">
                  <el-card header="详细资料">
                    <el-form-item label="电话">
                      <span>{{ colDetailProps.row.tel }}</span>
                    </el-form-item>
                    <el-form-item label="传真">
                      <span>{{ colDetailProps.row.fax }}</span>
                    </el-form-item>
                    <el-form-item label="地址">
                      <span>{{ colDetailProps.row.address }}</span>
                    </el-form-item>
                    <el-form-item label="组织全称">
                      <span>{{ colDetailProps.row.organName }}</span>
                    </el-form-item>
                    <el-form-item label="订单传真">
                      <span>{{ colDetailProps.row.orderFax }}</span>
                    </el-form-item>
                    <el-form-item label="财务传真">
                      <span>{{ colDetailProps.row.financeFax }}</span>
                    </el-form-item>
                    <el-form-item label="字母简称">
                      <span>{{ colDetailProps.row.shortCode }}</span>
                    </el-form-item>
                  </el-card>
                </el-col>
                <el-col :span="8">
                  <el-card
                    header="组织公章"
                    style="text-align: center;"
                  >
                    <el-image
                      :src="sealPhotoUrl(colDetailProps.row.multiFile)"
                      fit="cover"
                      style="width: 260px; height: 260px"
                    >
                      <div slot="placeholder">
                        加载中...
                      </div>
                      <div slot="error">
                        <el-image
                          :src="error404"
                          fit="cover"
                          style="width: 260px; height: 260px"
                        />
                      </div>
                    </el-image>
                  </el-card>
                </el-col>
              </el-row>
            </el-form>
          </template>
        </pl-table-column>
        <pl-table-column
          label="组织编码"
          prop="organCode"
          align="center"
          sortable
          sort-by="organCode"
          :filters="columnFilters.organCode"
          :filter-method="columnFilterHandler"
        >
          <template slot-scope="scope">
            <span>{{ scope.row.organCode }}</span>
          </template>
        </pl-table-column>
        <pl-table-column
          label="组织简称"
          prop="shortName"
          min-width="150px"
          align="center"
          sortable
          sort-by="shortName"
          :filters="columnFilters.shortName"
          :filter-method="columnFilterHandler"
        >
          <template slot-scope="scope">
            <span>{{ scope.row.shortName }}</span>
          </template>
        </pl-table-column>
        <pl-table-column
          label="集团"
          prop="groupName"
          align="center"
          sortable
          sort-by="groupName"
          :filters="columnFilters.groupName"
          :filter-method="columnFilterHandler"
        >
          <template slot-scope="scope">
            <span>{{ scope.row.groupName }}</span>
          </template>
        </pl-table-column>
      </pl-table>
    </div>
    <!-- 新增修改 -->
    <el-dialog
      :title="$t('route.organization') + '--' + $t('table.'+ dialogStatus)"
      :visible.sync="dialogFormVisible"
      top="2vh"
      :close-on-click-modal="false"
      custom-class="dialog-title-background"
    >
      <el-form
        ref="orgDataForm"
        :rules="rules"
        :model="temp"
        label-position="left"
        label-width="80px"
        style="width: 400px; margin-left:50px;"
      >
        <el-form-item
          label="名称"
          prop="organName"
        >
          <el-input
            v-model="temp.organName"
            placeholder="名称"
          />
        </el-form-item>
        <el-form-item
          label="所属集团"
          prop="groupId"
        >
          <el-select
            v-model="temp.groupId"
            size="mini"
            placeholder="请选择集团"
          >
            <el-option
              v-for="item in groups"
              :key="item.groupCode"
              :label="item.groupName"
              :value="item.groupId"
            >
              <span style="float: left">{{ item.groupCode }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.groupName }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="业务类型"
          prop="businessType"
        >
          <el-select
            v-model="temp.businessType"
            size="mini"
            multiple
            collapse-tags
            placeholder="请选择业务类型"
          >
            <el-option
              v-for="item in businessTypeList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="电话">
          <el-input
            v-model="temp.tel"
            placeholder="电话号码"
          />
        </el-form-item>
        <el-form-item label="传真">
          <el-input
            v-model="temp.fax"
            placeholder="传真"
          />
        </el-form-item>
        <el-form-item label="地址">
          <el-input
            v-model="temp.address"
            placeholder="地址"
            @click.native="handleOpenMap"
          />
        </el-form-item>
        <el-form-item
          label="简称"
          prop="shortName"
        >
          <el-input
            v-model="temp.shortName"
            placeholder="简称"
          />
        </el-form-item>
        <el-form-item
          label="字母编码"
          prop="shortCode"
        >
          <el-input
            v-model="temp.shortCode"
            placeholder="字母编码"
            maxlength="4"
            @input="handShort"
          />
        </el-form-item>
        <el-form-item label="订单传真">
          <el-input
            v-model="temp.orderFax"
            placeholder="订单传真"
          />
        </el-form-item>
        <el-form-item label="财务传真">
          <el-input
            v-model="temp.financeFax"
            placeholder="财务传真"
          />
        </el-form-item>
        <el-form-item label="电子公章">
          <el-upload
            class="seal-wrapper"
            action="#"
            :show-file-list="false"
            :auto-upload="false"
            :on-change="handlePhotoUpload"
          >
            <img
              v-if="temp.multiFile"
              :src="sealPhotoUrl(temp.multiFile)"
              :alt="temp.shortName"
            >
            <div
              v-else
              class="upload-tip"
            >
              <i class="el-icon-upload upload-icon" />
              <div class="el-upload__text"><em>点击上传公章</em></div>
            </div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div
        slot="footer"
        class="dialog-footer"
      >
        <el-button
          class="pause-button"
          @click="handleCancel"
        >
          {{ $t('table.cancel') }}
        </el-button>
        <el-button
          type="primary"
          @click="dialogStatus==='add'?createData():updateData()"
        >
          {{ $t('table.confirm') }}
        </el-button>
      </div>
    </el-dialog>
    <amap
      :visible.sync="mapDialog"
      :location="location"
      @getLocation="getLocation"
    />
  </div>
</template>

<script>
import Amap from '@/components/Amap'
import Error404 from '@/assets/404_images/404.png'
import { getList, addOneByForm, updateOneByForm, deleteItem } from '@/api/basic-data'
import { getConstantByType } from '@/utils/erp'

export default {
  name: 'Organization',
  components: {
    Amap
  },
  data() {
    return {
      // 地图
      location: '',
      mapDialog: false,
      groups: [],
      constants: [],
      filterCondition: {
        groupId: undefined
      },
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            picker.$emit('pick', [start, end])
          }
        }]
      },
      tableRef: 'orgDataTable',
      list: [],
      listLoading: true,
      temp: {
        organId: '',
        organName: '',
        groupId: '',
        businessType: "",
        tel: '',
        fax: '',
        address: '',
        shortName: '',
        shortCode: '',
        multiFile: '',
        orderFax: '',
        financeFax: ''
      },
      currentRow: null,
      dialogFormVisible: false,
      dialogStatus: 'add',
      textMap: {
        update: 'Edit',
        create: 'Create'
      },
      downloadLoading: false,
      error404: Error404,
      fileList: [],
    }
  },
  computed: {
    rules: function () {
      return {
        organName: [{ required: true, message: '请输入名称', trigger: 'blur' }],
        groupId: [{ required: true, message: '请选择组织', trigger: 'blur' }],
        businessType: [{ required: true, message: '请选择业务类型', trigger: 'blur' }],
        shortName: [{ required: true, message: '请输入简称', trigger: 'blur' }],
        shortCode: [{ required: true, message: '请输入四个英文字母', trigger: 'blur' }]
      }
    },
    columnFilters: function () {
      return {
        organCode: this.list.map(item => {
          return {
            text: item.organCode,
            value: item.organCode
          }
        }).filter((element, index, self) => { // 去重
          return self.findIndex(el => el.value === element.value) === index
        }),
        shortName: this.list.map(item => {
          return {
            text: item.shortName,
            value: item.shortName
          }
        }).filter((element, index, self) => { // 去重
          return self.findIndex(el => el.value === element.value) === index
        }),
        groupName: this.list.map(item => {
          return {
            text: item.groupName,
            value: item.groupName
          }
        }).filter((element, index, self) => { // 去重
          return self.findIndex(el => el.value === element.value) === index
        })
      }
    },
    businessTypeList: function () {
      return getConstantByType(this.constants, 212)
    }
  },
  created() {
    this.getGroups()
    this.getList()
    this.getConstants()
  },
  methods: {
    // 集团数据
    async getGroups() {
      const res = await getList('group')
      this.groups = res.data.pageItems
    },
    // 组织数据
    async getList() {
      this.listLoading = true
      const params = Object.assign({}, this.filterCondition)
      const res = await getList('getOrgan', params)
      this.list = res.data.pageItems
      this.listLoading = false
    },
    // 常量
    async getConstants() {
      const res = await getList('constant')
      this.constants = res.data.pageItems
    },
    setTemp(tmp) {
      Object.assign(this.temp, tmp)
      this.temp.businessType = tmp.businessType.split(',')
    },
    resetTemp() {
      this.temp = {
        organId: '',
        organCode: '',
        organName: '',
        groupId: '',
        // groupCode:'',
        businessType: '',
        tel: '',
        fax: '',
        address: '',
        shortName: '',
        // shortId:'',
        shortCode: '',
        multiFile: '',
        orderFax: '',
        financeFax: ''
      }
    },
    // 条件搜索
    handleChangeGroup(value) {
      if (!value) {
        this.filterCondition.groupId = undefined
      }
      this.getList()
      this.resetTemp()
    },
    // 字母编码
    handShort(value) {
      value = value.replace(/[^a-zA-Z]/g, '')
      this.temp.shortCode = value
    },
    // 新增
    handleCreate() {
      this.resetTemp()
      if (this.groups.length > 0) {
        this.temp.groupId = this.groups[0].groupId
      }
      this.dialogStatus = 'add'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['orgDataForm'].clearValidate()
      })
    },
    // 修改
    handleUpdate() {
      if (!this.currentRow) {
        this.$message({
          showClose: true,
          message: '请选择一条记录',
          type: 'warning',
          center: true
        })
        return
      }
      this.setTemp(this.currentRow)
      this.dialogStatus = 'edit'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['orgDataForm'].clearValidate()
      })
    },
    // 关闭
    handleCancel() {
      this.$confirm('是否放弃保存?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.dialogFormVisible = false
        this.resetTemp()
        this.$refs['orgDataForm'].setCurrentRow()
      }).catch(() => {
      })
    },
    // 弹框新增
    createData() {
      this.$refs['orgDataForm'].validate(async (valid) => {
        if (valid) {
          const res = await addOneByForm('organization', this.temp)
          console.log('this.temp: ', this.temp);
          if (res) {
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '创建成功',
              type: 'success',
              duration: 2000
            })
            this.getList()
            this.resetTemp()
          }
        } else {
          return false
        }
      })
    },
    // 弹框修改
    updateData() {
      this.$refs['orgDataForm'].validate(async (valid) => {
        if (valid) {
          const res = await updateOneByForm('organization', this.temp)
          if (res.code === 200) {
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '更新成功',
              type: 'success',
              duration: 2000
            })
          }
          this.getList()
          this.resetTemp()
        } else {
          return false
        }
      })
    },
    // 删除
    async handleDelete() {
      if (!this.temp.organId) {
        this.$message({
          showClose: true,
          message: '请选择一条记录',
          type: 'warning',
          center: true
        })
        return
      }
      this.$confirm('确认要删除该行吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const res = await deleteItem('organization', { organId: this.temp.organId })
        if (res.code === 200) {
          this.$notify({
            title: '成功',
            message: '删除成功',
            type: 'success',
            duration: 2000
          })
        }
        this.getList()
        this.resetTemp()
      }).catch(() => {
      })
    },
    // 刷新
    handleRefresh() {
      this.getGroups()
      this.getList()
      this.resetTemp()
    },
    // 表格点击事件
    handelRowClick(row, column, event) {
      this.setTemp(row)
    },
    handleCurrentRowChange(row) {
      this.currentRow = row
    },
    // 电子公章
    handlePhotoUpload(file) {
      const reader = new FileReader()
      reader.readAsDataURL(file.raw)
      reader.onload = () => {
        this.temp.multiFile = reader.result.substring(reader.result.indexOf(',') + 1)
      }
    },
    columnFilterHandler(value, row, column) {
      const property = column['property']
      return row[property] === value
    },
    sealPhotoUrl: function (multiFile) {
      return 'data:image/png;base64,' + multiFile
    },
    // 地图地址
    handleOpenMap() {
      this.location = this.temp.address
      this.mapDialog = true
    },
    getLocation(location) {
      this.temp.longitude = location.longitude
      this.temp.latitude = location.latitude
      this.temp.address = location.address
    }
  }
}
</script>

<style lang="scss">
.seal-wrapper {
  width: 200px;
  height: 200px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  text-align: center;
  img {
    margin-top: 8px;
    height: 180px;
  }
  .upload-tip {
    margin-top: 70px;
  }
}
</style>
